package com.gxa.xiaoucomeshome.exceptionHander;

import com.gxa.xiaoucomeshome.exception.BusinessException;
import com.gxa.xiaoucomeshome.utils.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author Administrator
 */
@RestController
@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler(Throwable.class)
    public Map businessExceptionHandler(Exception e) throws Exception{
        JsonResult jsonResult = new JsonResult();
        if (e instanceof BusinessException){
            BusinessException be = (BusinessException) e;
            jsonResult.setCode(be.exceptionCode.getCode());
            jsonResult.setMsg(be.exceptionCode.getMessage());
        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("服务器开小差了,请稍后再试");
            //记录日志
            //生成系统日志
            //异常发生年月日时间
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            //异常日志文件名/路径
            File file = new File("/usr"+ File.separator+"log"+File.separator + "error_"+format+".log");
            //创建字节输出流对象,且追加写入
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            //转化为字符输出流
            OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
            //写入异常发生的原因,时间,打印栈轨迹
            String format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            //异常发生详细时间
            writer.write("异常发生时间:"+format1+"\n");
            StringBuilder builder = new StringBuilder();
            //异常类型
            builder.append("异常类型:").append(e.toString()).append("\n");
            //异常发生的原因
            builder.append("异常发生的原因:").append(e.getMessage()).append("\n");
            //栈轨迹
            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement stackTraces : stackTrace) {
                builder.append(stackTraces.toString()).append("\n");
            }
            writer.write(builder.toString());
            writer.write("--------------------------------------------------------------------------");
            writer.write("\n");
            writer.flush();
            writer.close();
        }
        return jsonResult.getMap();
    }
}
